const mongoose = require('mongoose');

// 数据库连接配置
const connectDB = async () => {
  try {
    const conn = await mongoose.connect(process.env.MONGO_URI, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    console.log(`MongoDB连接成功: ${conn.connection.host}`);
  } catch (error) {
    console.error(`MongoDB连接失败: ${error.message}`);
    // 连接失败时退出进程
    process.exit(1);
  }
};

// 关闭数据库连接
const disconnectDB = async () => {
  try {
    await mongoose.disconnect();
    console.log('MongoDB连接已关闭');
  } catch (error) {
    console.error(`关闭MongoDB连接失败: ${error.message}`);
  }
};

module.exports = {
  connectDB,
  disconnectDB
};